package mis510.homefinders;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import mis510.homefinders.Map.JavaScriptInterface;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class Transportation extends Activity{
	 static String search_address = null;
	 static String comm_address = null;
	 static String php_rep;
	 HttpClient httpclient = new DefaultHttpClient();
	 HttpPost httppost = new HttpPost("http://54.214.11.178/json_mobile.php");
	 Button bk_btn;
	 Button search_btn;
	 RadioButton chosen_method;
	 EditText fav_address;
	 TextView ws_score;
	 TextView ws_descript;
	 TableRow ws_tableRow;
	 Intent nextActivity;
	 RadioGroup trans_method;
	 ArrayList<String> trans_info = new ArrayList<String>();
	 ListView transinfo_list;
	 ArrayAdapter<String> arrayAdapter;
	 String result;
		private static final DocumentBuilderFactory dbFac;
	    private static final DocumentBuilder docBuilder;
	    static
	    {
	        try
	        {
	            dbFac = DocumentBuilderFactory.newInstance();
	            docBuilder = dbFac.newDocumentBuilder();
	        }
	        catch(ParserConfigurationException e)
	        {
	            throw new RuntimeException(e);
	        }
	    }
	    private static final String WS_URL = "http://api.walkscore.com/score?format=xml";
	    private static final String WSID = "e6b9ab999aecb4b879793f684a751825";
		private static String walkscoreT = null;
		private static String wsdesT = null;
	 
	 public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.transportation);
	        System.out.println("trans");
	        
	     
	        Intent intent = this.getParent().getIntent();
			Bundle bundle = intent.getExtras();
			search_address = bundle.getString("address");
			System.out.println("passed address in trans tab: "+search_address);	 

     
			fav_address = (EditText)findViewById(R.id.fav_address);
			ws_score = (TextView)findViewById(R.id.ws_score);
			ws_descript = (TextView)findViewById(R.id.ws_descript);
			search_btn = (Button)findViewById(R.id.search_button);
			bk_btn = (Button)findViewById(R.id.bk_btn);
			trans_method = (RadioGroup) findViewById(R.id.trans_method);
			transinfo_list = (ListView)findViewById(R.id.transinfo_list);
			arrayAdapter = new ArrayAdapter<String>(this, R.layout.list_item, trans_info);
			
			bk_btn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
         	nextActivity = new Intent(Transportation.this, SearchProperty.class);
         	startActivity(nextActivity);
         }
     });
			
			search_btn.setOnClickListener(new View.OnClickListener() {
		         @Override
		         public void onClick(View view) {
		        	 comm_address = fav_address.getText().toString();
		        	 StringTokenizer st = new StringTokenizer(comm_address, ",");
		             if (String.valueOf(comm_address).trim().length()>0 && st.countTokens() == 3)
		        	 {
		            	 int selectedId = trans_method.getCheckedRadioButtonId();
		            	 chosen_method = (RadioButton)findViewById(selectedId);
		            	 System.out.println(selectedId);
		            	 System.out.println("des_address: "+comm_address);
		            	 new walkscore().execute(search_address.trim());
		            	 new phpdata().execute(search_address.trim(),comm_address.trim(),chosen_method.getText().toString().toLowerCase());
		        	 }
		             else 
		            	 {
		            	    Toast toast_info = Toast.makeText(getApplicationContext() , "Please provide an address in correct format, e.g. stree, city, state", Toast.LENGTH_SHORT);
	            		    toast_info.show();
		            	 }
		         }
			  });
	 }
	 			
	 
	 			public class walkscore extends AsyncTask<String, Void, String>
	 			{
     	 
	 				protected String doInBackground(String...search_address)
	 				{
	 					String[] walkscore_add = search_address;
	 					StringTokenizer st = new StringTokenizer(walkscore_add[0], ",");
	 					String street = st.nextToken();
	 					String city = st.nextToken();
	 					String state = st.nextToken();
	 					String walkscore_address = street+" "+city+" "+state;
	 					LongLatService tDirectionService = new LongLatService();
	 				    tDirectionService.getLongitudeLatitude(walkscore_address);
	 				    Document wsDoc;
					try {
						wsDoc = docBuilder.parse(WS_URL + 
						            "&address=" + URLEncoder.encode(walkscore_address, "utf-8") + 
						            "&lat=" + tDirectionService.getLat() +
						            "&lon=" + tDirectionService.getLong() +
						            "&wsapikey=" + WSID);
					
	 					Element status = (Element)wsDoc.getElementsByTagName("status").item(0);
	 					if (status != null)
	 			        {
	 						String statusT = status.getTextContent();
	 						if(statusT.equals("1")){
	 							Element walkscore = (Element)wsDoc.getElementsByTagName("walkscore").item(0);
	 							if (walkscore != null)
	 					        {
	 								walkscoreT = walkscore.getTextContent();
	 					        }
	 							Element wsdescription = (Element)wsDoc.getElementsByTagName("description").item(0);
	 							if (wsdescription != null)
	 					        {
	 								wsdesT = wsdescription.getTextContent();
	 					        }
	 							System.out.println("WalkScore for "+walkscore_address+"  "+walkscoreT);
	 							System.out.println("Description  " +wsdesT);
	 							
	 							result = walkscoreT +","+ wsdesT;
	 						}
	 						else 
	 						{
	 							System.out.println("WalkScore isn't availible");
	 							result = "WalkScore isn't availible";
	 						}
	 						
	 			        }
	 					
					} catch (SAXException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("result"+result);
					return result;
	 			}
	 			
	 				protected void onPostExecute(String result) 
	 				{
	 					StringTokenizer st = new StringTokenizer(result, ",");
	 					if(st.countTokens() == 2)
	 					{
	 						String ws_score_asyn = st.nextToken();
	 						ws_score.setText(ws_score_asyn);
	 						String ws_des_asyn = st.nextToken();
	 						ws_descript.setText("Walkability: "+ws_des_asyn);
	 					}
	 					else
	 						ws_score.setText(st.nextToken());	 					
	 				}
	 				
	 			}
	 			
		         
		        public class phpdata extends AsyncTask<String, Void, String>
		 	    {
		        	 
		        	 protected String doInBackground(String...comm_address)
		 	        {
		        		 String[] comm_address_asyn = comm_address;
		        		 //String reverseString = null;
		        	 
		        	 try {  
//		        		 	System.out.println("address in async "+comm_address_asyn[0]);
//		        		 	System.out.println("address in async "+comm_address_asyn[1]);
//		        		 	System.out.println("address in async "+comm_address_asyn[2]);
		        		    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
		        		    nameValuePairs.add(new BasicNameValuePair("ori_address", comm_address_asyn[0]));
		        		    nameValuePairs.add(new BasicNameValuePair("des_address", comm_address_asyn[1]));
		        		    nameValuePairs.add(new BasicNameValuePair("transportation", comm_address_asyn[2]));
		        		    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		        		    ResponseHandler<String> responseHandler = new BasicResponseHandler();
		        	        php_rep = httpclient.execute(httppost, responseHandler);
		        	        System.out.println("got response "+php_rep);
		        	        //reverseString = response;
		        	       // Toast.makeText(Transportation.this, php_rep, Toast.LENGTH_LONG).show();

		        		} catch (ClientProtocolException e) {
		        		   System.out.println("Client protokol exception ");
		        		} catch (IOException e) {
		        		    System.out.println("IO exception "+e.getMessage());
		        		}
		        	 //postData(comm_address);
//		         	nextActivity = new Intent(Transportation.this, SearchProperty.class);
//		         	startActivity(nextActivity);
		        	 return php_rep;
		         }
		        	 
		        	 protected void onPostExecute(String php_rep) {
		        		 System.out.println("after execute: "+php_rep);
		        		 //String response = php_rep.replace("<br>", ",");
		        		 StringTokenizer st = new StringTokenizer(php_rep, "#");
		        		 while(st.hasMoreTokens())
		        			 trans_info.add(st.nextToken());
		        		 for (int i = 0; i < trans_info.size(); i++) {
			    		     System.out.println(trans_info.get(i));
			    		}
		        		 transinfo_list.setAdapter(arrayAdapter); 
		        		 
		        			 
		        	 }
		 	    }
	 }	 
		   						

